package top.cwk.dubbo.web.config;

import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import top.cwk.dubbo.entity.serviceJson.ServiceJsonBean;
import top.cwk.dubbo.entity.util.BaseUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ServiceJsonBeanListener
 * @Description servlet监听器，初始化将service.json读取到ServletContext
 * @Author 维康
 * @Date 2018/7/26 16:27
 * @Version 1.0
 **/
@Configuration
public class ServiceJsonBeanListener implements ServletContextListener {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static Map<Long,ServiceJsonBean> SERVICE_MAP = new HashMap<>();

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        File file = null;
        try {
            file = file = ResourceUtils.getFile("classpath:service.json");
            String jsonStr = BaseUtils.readFileContent(file);
            JSONArray array = JSONArray.fromObject(jsonStr);
            ServiceJsonBean[] arrayBean = (ServiceJsonBean[]) JSONArray.toArray(array,ServiceJsonBean.class);
            List<ServiceJsonBean> list = CollectionUtils.arrayToList(arrayBean);
            try{
                //将list转换为以serviceId 为主键的Map
                SERVICE_MAP = list.parallelStream().collect(
                        Collectors.toMap(ServiceJsonBean::getServiceId, bean -> bean)
                );
            }catch (IllegalStateException e){
                logger.error("service.json 配置出错,serviceId不得重复！",e);
            }
            servletContextEvent.getServletContext().setAttribute("SERVICE_MAP" , SERVICE_MAP);
            logger.debug("读取 service.json : "+SERVICE_MAP.toString());
        } catch (FileNotFoundException e2) {
            logger.error(" service.json 配置出错,找不到文件！",e2);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
